local ngx     = ngx
local pairs   = pairs
local table   = table
local tonumber = tonumber
local table_concat = table.concat
local loadstring = table.loadstring
local utils   = require("modules.business_common.business_utils")
local config  = require("modules.business_common.business_config")
local http    = require("modules.business_common.utils.business_http")

local FOO = {
    _VERSION       = '0.12.1',
}


local gen_ma_gate_token = function (uin_, time_, cmd_, ext_)
    return ngx.md5((uin_ or '')..'#LY1006#'..time_..'#'..cmd_..'#'..(ext_ or ''))
end


local http_request = function(uin, request)
    if not (request and request.cmd) then
        return nil
    end

    request.uin   = uin
    request.time  = ngx.time()
    request.token = gen_ma_gate_token(request.uin, request.time, request.cmd)

    local server = config.get_profile_server_url(uin)
    local response = loadstring(http.Get(server, request) or 'nil')
    if response and tonumber(response.ret) == 0 then
        return true, response;
    end
    -- 失败日志
    http.Log(utils.hm.to_str({server = server, request = request, response = response}))
    return false, response;
end


--! @ 查询 已拥有的永久头像框
--! @ 返回： {id，id1,...}
FOO.query_owned_box_account = function(dst_uin, src_uin)
    src_uin = src_uin or ngx.ctx.m_params.uin
    dst_uin = dst_uin or ngx.ctx.m_params.uin
    local succ, result = http_request(dst_uin, {
        cmd      = "getProfile",
        op_uin   = src_uin,
    })
    if not succ then
        return false, {}
    end

    return true, utils.table2list((result.profile or {}).head_frames)
end


--增加头像框
FOO.open_head_frame = function(frame_id, dst_uin, src_uin)
    src_uin = src_uin or ngx.ctx.m_params.uin
    dst_uin = dst_uin or ngx.ctx.m_params.uin
    local succ, result = http_request(dst_uin, {
        cmd      = 'openHeadFrame',
        op_uin   = src_uin,
        frame_id = frame_id,
    })
    if not succ then
        return false,{}
    end
    return true,result
end


-- !开启/关闭vip头像
local VIPHeadFrameOp = function(cmd, frame_lst, dst_uin, src_uin)
    src_uin = src_uin or ngx.ctx.m_params.uin
    dst_uin = dst_uin or ngx.ctx.m_params.uin
    local succ, result = http_request(dst_uin, {
        cmd        = cmd,
        op_uin     = src_uin,
        frame_list = table_concat(frame_lst or {}, ','),
    })
    if not succ then
        return false, {}
    end

    return true, result
end

FOO.open_vip_head_frame = function (frame_lst, dst_uin, src_uin)
    return VIPHeadFrameOp('openHeadFrameVIP', frame_lst, dst_uin, src_uin)
end

FOO.lock_vip_head_frame = function (frame_lst, dst_uin, src_uin)
    return VIPHeadFrameOp('lockHeadFrameVIP', frame_lst, dst_uin, src_uin)
end

return FOO